﻿namespace CraftingCode.SymbolicCalculator
{
    using System.Collections.Generic;
    using System.Linq;

    public static class Parser
    {
        public static Node Parse(string expression)
        {
            var tokenizer = new Tokenizer();

            return tokenizer
                .TokenizeExpression(expression)
                .BuildExpressionTree();
        }

        private static Node BuildExpressionTree(this IList<Token> tokens)
        {
            var topToken = tokens
               .OrderByDescending(token => token.Priority)
               .First();
            var topTokenIndex = tokens.IndexOf(topToken);

            var node = topToken.Node;

            var addition = node as Addition;
            if (addition != null)
            {
                addition.Left = BuildExpressionTree(tokens.Take(topTokenIndex).ToList());
                addition.Right = BuildExpressionTree(tokens.Skip(topTokenIndex + 1).ToList());
            }

            return node;
        }
    }
}
